/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 08 - 29
 * Time: 16:46
 */
//牛客 判断是不是平衡二叉树
class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
      this.val = val;
    }
}
public class Solution1 {
    //法一 官方推荐方法
    public boolean IsBalanced_Solution (TreeNode pRoot) {
        if(pRoot == null) return true;
        if(Math.abs(getHeight(pRoot.left) - getHeight(pRoot.right)) <= 1 && IsBalanced_Solution (pRoot.left) && IsBalanced_Solution (pRoot.right)) {
            return true;
        }
        return false;
    }
    public int getHeight(TreeNode root) {
        if (root == null) return 0;
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
    }

    //法二 官方方法
    public boolean IsBalanced_Solution1 (TreeNode pRoot) {
        if(pRoot == null) return true;
        return getHeight1(pRoot) > 0;
    }
    public int getHeight1(TreeNode root) {
        if (root == null) return 0;
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        if(leftHeight >= 0 && rightHeight >= 0 && Math.abs(leftHeight - rightHeight) <= 1) {
            return Math.max(leftHeight, rightHeight) + 1;
        }else {
            return -1;//若不是平衡二叉树则在获取树的高度时返回-1，即在获取树的高度的过程中判断是否为平衡二叉树
        }
    }
}
